package handlers

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"like-it/cahe"
	"like-it/models"
	"like-it/pkg"
	"strconv"
	"time"
)

func Register(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不能为空",
		})
		return
	}
	data := models.User{
		Username: username,
		Password: pkg.Md5(password),
	}
	err := models.DB.Create(&data).Debug().Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "注册失败",
		})
		return
	} else {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "注册成功",
		})
		return
	}
}
func Login(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "用户名或密码为空",
		})
		return
	}
	redis_key := "login_error_" + username
	errCount, _ := cahe.Rdb.Get(cahe.Ctx, redis_key).Int()
	if errCount >= 3 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误三次禁止登录",
		})
		return
	}
	var user models.User
	err := models.DB.Where("username=?", username).Debug().First(&user).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "用户查询失败",
		})
		return
	}
	if user.ID == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "用户不存在",
		})
		return
	}
	if user.Password != pkg.Md5(password) {
		cahe.Rdb.Incr(cahe.Ctx, redis_key)
		if errCount == 2 {
			cahe.Rdb.Set(cahe.Ctx, redis_key, 3, time.Hour*2)
			c.JSON(200, gin.H{
				"code": 500,
				"msg":  "密码错误三次,封禁2个小时",
			})
			return
		}
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "登录失败",
		})
		return
	}
	token := pkg.TokenHandler(strconv.Itoa(int(user.ID)))
	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "登录成功",
		"data":  user,
		"token": token,
	})
	return
}
func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.Query("page"))
	size, _ := strconv.Atoi(c.Query("size"))
	offest := (page - 1) * size

	var users []models.User
	redis_key := "list_page_" + strconv.Itoa(page)
	caheData, _ := cahe.Rdb.Get(cahe.Ctx, redis_key).Result()
	if caheData == "" {
		models.DB.Offset(offest).Limit(size).Debug().Find(&users)
		jsonData, _ := json.Marshal(users)
		cahe.Rdb.Set(cahe.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(caheData), &users)
	}
	var total int64
	models.DB.Model(&models.User{}).Count(&total)
	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "ok",
		"data":  users,
		"total": total,
	})
	return
}
